package org.cncy;


import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpsUtils {
    private static Logger LOG = LoggerFactory.getLogger(HttpsUtils.class);
    private static CloseableHttpClient httpClient = null;


    public static void main(String[] args) throws Exception {
        String bogy = "{\"lockOp\":\"LOCK\",\"lockPassword\":\"5MJRqBq3skfTj0KNqMsFo/zaQE0FATAMTQEQJy/2l8n8x8Ndzh+sGTyQIzOfvYpU2PlLqz5aqFAf3SZEEYR6Ti5HmpkgTaqXJWFwDq84Satz45FEp80sbMybwFIfRrYwgGQ4ve5ztrgleIOOtlwjRF4GYw4r7axV62wavLiTTEE=\",\"deviceIds\":\"687\"}";
        StringEntity stringEntity = new StringEntity(bogy);
        HashMap<String, String> header = new HashMap<>();
        header.put("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJyb2xlIjoiMTAiLCJ1c2VyX2lkIjoiYWRtaW4iLCJuYW1lIjoiYWRtaW4iLCJ0ZW5hbnRJZCI6Im1kbSIsImZ1bGxuYW1lIjoiQWRtaW5pc3RyYXRvciIsImV4cCI6MTcwNDgxMDU4OSwiYXVkIjoiVUVNIiwiaXNzIjoiaHR0cHM6Ly9iYWNrZW5kLm5hdGlvbnNreS5jb20ifQ.qSVcLD1IgRtf0bK2hk8omnR19VvLdoteQG8GvJQVcg0riN0PEwLBNCzplR1c3cIbQqNJw-Nd7ySzMPNjQ-NXMQ");
        header.put("Content-Type","application/json;charset=UTF-8");
        // byte[] bytes = Utils.doPost("https://172.16.81.6/mdm/devices/commands/lock", bogy.getBytes(StandardCharsets.UTF_8));
        String a = sendData(stringEntity, "https://120.46.144.252/mdm/devices/commands/lock", header);

        System.out.println(a);
    }

    /**
     * 绕过证书认证
     *
     * @return
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static CloseableHttpClient createHttpsClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        //SSLContextBuilder builder = new SSLContextBuilder();
        //builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        //4.3版本之前用这个
        //SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(
        //builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //4.3版本之后用这个
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslcontext,
                new String[]{"TLSv1", "TLSv1.2"}, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);


        Registry<ConnectionSocketFactory> registry = RegistryBuilder.
                <ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", sslcsf)
                .build();


        // TODO: 2023/12/13 初始化连接池的时候，需要注册https的配置信息，否则证书异常
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(2000);
       // cm.setDefaultMaxPerRoute(500);

        RequestConfig requestConfig = RequestConfig.custom().
                setConnectionRequestTimeout(15000)
                .setConnectTimeout(10000)
                .setSocketTimeout(15000)
                .build();


        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslcsf)
                .setConnectionManager(cm).setDefaultRequestConfig(requestConfig)
                .build();
        return httpClient;
    }


    public static String sendData(HttpUriRequest request, String url) {
        CloseableHttpResponse httpResponse = null;
        String resultString = null;
        try {
            CloseableHttpClient httpClient = HttpsUtils.createHttpsClient();
            CloseableHttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    resultString = EntityUtils.toString(responseEntity, "utf-8");
                    EntityUtils.consume(responseEntity);//关闭资源
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                LOG.debug("请求流关闭完成");
            } catch (IOException e) {
                LOG.debug("请求流关闭出错");
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static byte[] doPost(String url, byte[] body) throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        HttpPost httpPost = new HttpPost(url);
        ByteArrayEntity entiry = new ByteArrayEntity(body);
        httpPost.setEntity(entiry);
        CloseableHttpClient httpClient = HttpsUtils.createHttpsClient();
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        return EntityUtils.toByteArray(httpResponse.getEntity());
    }

    public static String sendData(HttpEntity httpEntity, String url, Map<String, String> header) {
        CloseableHttpResponse httpResponse = null;
        String resultString = null;
        try {
            HttpPut httpPut = new HttpPut(url);
            header.forEach((k, v) -> {
                httpPut.addHeader(k, v);
            });
            httpPut.setEntity(httpEntity);
            CloseableHttpClient httpClient = HttpsUtils.createHttpsClient();
            CloseableHttpResponse response = httpClient.execute(httpPut);
            LOG.debug("response = {}", response);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                resultString = EntityUtils.toString(responseEntity, "utf-8");
                EntityUtils.consume(httpEntity);//关闭资源
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                LOG.debug("请求流关闭完成");
            } catch (IOException e) {
                LOG.debug("请求流关闭出错");
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送https请求
     *
     * @throws Exception
     */
    public static String sendByHttp(Map<String, Object> params, String url, Map<String, String> header) {
        List<NameValuePair> listNVP = new ArrayList<NameValuePair>();
        if (params != null) {
            for (String key : params.keySet()) {
                listNVP.add(new BasicNameValuePair(key, params.get(key).toString()));
            }
        }
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listNVP, "UTF-8");
            LOG.debug("创建请求httpPost-URL={},params={}", url, listNVP);
            return sendData(entity, url, header);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}